package com.dtguai.web.web.sys.service.impl;

import com.dtguai.web.base.service.impl.BaseServiceImpl;
import com.dtguai.web.common.error.ErrorCode;
import com.dtguai.web.common.exception.DefinedException;
import com.dtguai.web.util.constant.Constant;
import com.dtguai.web.util.redis.RedisUtil;
import com.dtguai.web.web.sys.dao.SysDefAdminDao;
import com.dtguai.web.web.sys.model.SysDefAdmin;
import com.dtguai.web.web.sys.service.SysDefAdminRoleService;
import com.dtguai.web.web.sys.service.SysDefAdminService;
import com.dtguai.web.web.sys.service.SysDefRoleService;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * @author: guoLiang
 * @date：2018-12-11 02:43:01
 */
@Service("sysDefAdminService")
public class SysDefAdminServiceImpl extends BaseServiceImpl<SysDefAdmin> implements SysDefAdminService {

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    private SysDefAdminRoleService sysDefAdminRoleService;

    @Autowired
    private SysDefRoleService sysDefRoleService;


    /**
     * 查询用户的所有权限
     *
     * @param adminId 管理员id
     */
    @Override
    public List<String> getAdminPermsList(Integer adminId) {
        return ((SysDefAdminDao) getMapper()).findPermsById(adminId);
    }

    /**
     * 修改密码
     *
     * @param adminId     管理员id
     * @param password    旧密码
     * @param newPassword 新密码
     */
    @Override
    public boolean updatePassword(Integer adminId, String password, String newPassword) {
        SysDefAdmin userEntity = new SysDefAdmin();
        userEntity.setPassword(newPassword);
        return ((SysDefAdminDao) getMapper()).updatePassword(adminId, password, newPassword) != 0;
    }

    /**
     * 添加用户 add
     *
     * @param admin 用户实体
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer add(SysDefAdmin admin) {
        admin.setCreateTime(new Date());

        String code = RandomStringUtils.randomAlphanumeric(20);
        admin.setPassword(new Sha256Hash(admin.getPassword(), code).toHex());
        admin.setCode(code);

        this.insertSelective(admin);

        //检查角色是否越权
        checkRole(admin);

        //保存用户与角色关系
        sysDefAdminRoleService.saveOrUpdate(admin.getId(), admin.getRoleIdList());

        return admin.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysDefAdmin admin) {
        if (!StringUtils.isBlank(admin.getPassword())) {
            admin.setPassword(new Sha256Hash(admin.getPassword(), admin.getCode()).toHex());
        }
        this.updateNotNull(admin);

        //检查角色是否越权
        checkRole(admin);

        //保存用户与角色关系
        sysDefAdminRoleService.saveOrUpdate(admin.getId(), admin.getRoleIdList());
    }

    /**
     * 检查角色是否越权
     */
    private void checkRole(SysDefAdmin admin) {

        if (admin.getRoleIdList() == null || admin.getRoleIdList().size() == 0) {
            return;
        }

        //如果不是超级管理员，则需要判断用户的角色是否自己创建
        if (getAdminId() == Constant.SUPER_ADMIN) {
            return;
        }

        //查询用户创建的角色列表
        List<Integer> roleIdList = sysDefRoleService.getRoleIdList(getAdminId());

        //判断是否越权
        if (!roleIdList.containsAll(admin.getRoleIdList())) {
            throw new DefinedException(ErrorCode.NOT_PERMISSION_ADD_ROLE_NOT_CREATE);
        }
    }

    @Override
    public void deleteBatchById(List<Integer> ids) {
        Example example = new Example(SysDefAdmin.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("id", ids);
        ((SysDefAdminDao) getMapper()).deleteByExample(example);
    }
}